package api

import (
	"github.com/gin-gonic/gin"
	"go_api/config"
	"go_api/model"
	"go_api/pkg/bcrypt"
	"go_api/pkg/validator"
	"go_api/request"
	"log"
)

type UserController struct {
	BaseController
}
type uploadImage struct {
	Url  string `json:"url"`
	Path string `json:"path"`
}

// user 上传图片
func (user UserController) UploadImage(c *gin.Context) {
	// 单文件
	file, _ := c.FormFile("file")
	log.Println(file.Filename)

	// 上传文件至指定的完整文件路径
	err := c.SaveUploadedFile(file, "./assets/upload/images/"+file.Filename)
	if err != nil {
		user.responseError(c, 1, "上传失败")
		return
	}
	url := config.GetEnv("WEB_HOST") + "/assets/upload/images/" + file.Filename
	uploadImage := uploadImage{Url: url, Path: "/assets/upload/images/" + file.Filename}
	user.responseSuccess(c, uploadImage)
}

// EditUser 编辑用户信息
func (user UserController) EditUser(c *gin.Context) {
	uId := c.GetInt("uId")
	if uId == 0 {
		user.responseError(c, 401, "缺少登陆信息")
		return
	}
	//数据验证
	var data request.EditUserRequest
	msg, ok := validator.ValidatorData(c, &data)
	if !ok {
		user.responseError(c, 1, msg)
		return
	}
	var err error
	var passwordStr string

	userModel := model.XUser{
		Name:  data.Name,
		Phone: data.Phone,
	}
	//检查手机号是否存在
	userInfo, _ := userModel.GetUserByPhone(data.Phone)
	if userInfo.ID > 0 && userInfo.ID != uId {
		user.responseError(c, 1, "手机号已注册")
		return
	}

	if data.HeadImg != "" {
		userModel.HeadImg = data.HeadImg
	}
	if data.Password != "" {

		//密码生成
		passwordStr, err = bcrypt.GetPasswordUtil().Encrypt(data.Password)
		if err != nil {
			user.responseError(c, 1, "密码生成失败")
			return
		}
		userModel.Password = passwordStr
	}

	err = userModel.EditUser(uId)
	if err != nil {
		user.responseError(c, 1, "更新失败")
	}
	user.responseSuccess(c, nil)
}

func (user UserController) CreateUser(c *gin.Context) {
	//数据验证
	var data request.CreateUserRequest
	msg, ok := validator.ValidatorData(c, &data)
	if !ok {
		user.responseError(c, 1, msg)
		return
	}
	//密码生成
	passwordStr, err := bcrypt.GetPasswordUtil().Encrypt(data.Password)
	if err != nil {
		user.responseError(c, 1, "密码生成失败")
		return
	}

	userModel := model.XUser{
		Name:     data.Name,
		Phone:    data.Phone,
		Password: passwordStr,
	}

	//检查手机号是否存在
	userInfo, _ := userModel.GetUserByPhone(data.Phone)
	if userInfo.ID > 0 {
		user.responseError(c, 1, "手机号已注册")
		return
	}

	err = userModel.CreateUser()
	if err != nil {
		user.responseError(c, 1, err.Error())
		return
	}

	user.responseSuccess(c, nil)
}
